import React, { Component, ComponentClass } from 'react';
import Taro, { Config } from '@tarojs/taro';
import {Image, Input, Picker, Text, View} from '@tarojs/components'
import {AtIcon, AtButton, AtTabs} from 'taro-ui'
import {
  ALIBABA_SELECTGOODSLIST,
  ALIBABA_SYNC_NOTICE_GOODS,
  ALIBABA_DETAILS,
  ALIBABA_UPDATE_ALIBABAGOODS,
  IDENTITY,
  ALIBABA_DELETE_ALIBABA_GOODS
} from '../../../constants/api'
import {clearSearch as clearSearchFunc, vcmonitor} from "../../../utils/tools";
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {http} from "../../../utils/http";
import {UserIdentity} from "../../../utils/server.interface";
import {user} from "../../../utils/user.service";
import './list.scss'

type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: any
  size: number
  thirdStoreName: string
  tipsNum: number
  supplierList: number
  queryData: any
  supplierChecked: string
  supplierIndex: number
  searchList: any
  currentSearchIndex: number
  failMessage: any
}

class Index extends Component {

  state: PageState = {
    failMessage: {
      show: false,
      message: ''
    },
    loadMoreStatus: 'loading',
    list: [],
    size: 10,
    thirdStoreName: '',
    tipsNum: 0,
    supplierList: 0,
    queryData: {
      type: 'supplier',
      supplier_id: '',
      search_status: '',
      pageSize: 10,
      pageNumber: 1
    },
    supplierChecked: '',
    supplierIndex: 0,
    searchList: [{title: '全部', value: -1}, {title: '待提交', value: 0}, {title: '审核中', value: 1}, {title: '审核失败', value: 3}, {title: '审核驳回', value: 4}],
    currentSearchIndex: 0
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this);
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity: any = await http.get<UserIdentity>(IDENTITY, {is_alibaba_store: 1})
      if (userIdentity && userIdentity.isSupplier) {
        let supplierChecked = ''
        let supplierIndex = Taro.getStorageSync('mySupplierIndex') || 0
        if (userIdentity.SupplierList.length > 0) {
          supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
          supplierChecked = userIdentity.SupplierList[supplierIndex].company
          this.state.queryData.supplier_id = userIdentity.SupplierList[supplierIndex].supplier_id
          Taro.setStorageSync('mySupplierIndex', supplierIndex)
        }
        this.setState({supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex})
      } else {
        Taro.showToast({
          title: '您还没有供应商，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
    this.getList()
  }

  async componentDidShow() {
    this.getList()
  }


  async getList() {
    this.page = 1
    const list = await this.getGoods()
    /*const list = [{
      "sid": 832,
      "inventory": 10,
      "no": "VC2211251010_1",
      "vc_status": 0,
      "status": "审核失败",
      "online_status": "待提交",
      "add_date": "2022-11-25T07:19:29.083+0000",
      "id": 138,
      "uuid": "8d789c48-94e4-4b26-b877-5759af8ded61",
      "mname": "哈妮鲁比小镇",
      "bname": null,
      "gname": "代金券三方测试勿拍",
      "error_message": "批量查询门店信息部分失败, 未搜到门店storeIds=1056231105",
      "item_id": null,
      "supplier_id": 4566,
      "shop_name": "哈妮鲁比小镇",
      "supplier_name": "初始供应商公司",
      "original_price": "10",
      "price": "0.01",
      "ticket_display_mode": null,
      "gmt": "2022-11-25 00:00:00至2022-11-26 23:59:59",
      "validity_type": "相对有效期",
      "validity_time": "10天",
      "category_name": "结婚花艺",
      "item_type": "代金券",
      "name": null,
      "showEdit": true,
      "showDelete": true,
      "showSee": false,
      "showEditStock": false,
      "showUp": false,
      "showDown": false,
      "showPush": true,
      "site_name": "微笑游-体验"
    }]*/
    this.setState({list})
  }

  page = 1

  async getGoods() {
    const {currentSearchIndex, searchList} = this.state
    if (this.state.queryData['supplier_id']) {
      const params = {
        page: this.page,
        size: this.state.size,
        supplierQuery: this.state.thirdStoreName,
        is_supplier: 1,
        is_app: 1,
        supplier_id: this.state.queryData['supplier_id'],
        status: searchList[currentSearchIndex].value < 0 ? '' : searchList[currentSearchIndex].value
      }
      const goodsData = await http.HGet(ALIBABA_SELECTGOODSLIST, params)
      if (goodsData.data && goodsData.data.data) {
        if (goodsData.currentPage < goodsData.totalPages) {
          this.setState({loadMoreStatus: 'more'})
        } else {
          this.setState({loadMoreStatus: 'noMore'})
        }
        return goodsData.data.data
      } else {
        this.setState({loadMoreStatus: 'noMore'})
        return []
      }
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getGoods()
      this.setState({list: [...old, ...newData]})
    }
  }

  searchConfirm() {
    this.page = 1
    this.getList()
  }

  async clearSearch() {
    await this.setState({thirdStoreName: ''}, () => {
      this.getList()
    })
  }

  input(value) {
    if (value) {
      this.setState({thirdStoreName: value})
    } else {
      clearSearchFunc();
    }
  }

  showTips(message, status) {
    console.log(status)
    if (status != '审核失败') {
      return
    }
    const { failMessage } = this.state
    failMessage.show = true
    failMessage.message = message
    this.setState({failMessage})
  }
  closeModel() {
    const { failMessage } = this.state
    failMessage.show = false
    this.setState({failMessage})
  }
  async deleteGoods(uuid,action?) {
    if (action == 'invalid') {
      const params = {
        action: action,
        uuid: uuid,
        is_supplier: 1,
        is_app: 1,
        supplier_id: this.state.queryData['supplier_id']
      }
      const goodsData = await http.HGet(ALIBABA_SYNC_NOTICE_GOODS, params)
      if (goodsData || goodsData !== false) {
        Taro.showToast({
          title: '删除成功！',
          icon: 'none',
        })
        this.getList()
      } else {
        Taro.showToast({
          title: goodsData.message,
          icon: 'none',
        })
      }
    }else {
      const params = {
        is_supplier: 1,
        is_app: 1,
        supplier_id: this.state.queryData['supplier_id'],
        uuid: uuid,
      }
      const goodsData = await http.HGet(ALIBABA_DELETE_ALIBABA_GOODS, params)
      if (goodsData || goodsData !== false) {
        Taro.showToast({
          title: '删除成功！',
          icon: 'none',
        })
        this.getList()
      }  else {
        Taro.showToast({
          title: goodsData.message,
          icon: 'none',
        })
      }
    }

  }
  async examine(uuid) {
    Taro.showToast({title: '加载中...', duration: 20000, mask: true, icon: 'loading'})
    let exForm = {
      is_supplier: 1,
      is_app: 1,
      supplier_id: this.state.queryData['supplier_id']
    }
    const res = await http.HGet(ALIBABA_DETAILS + uuid, exForm)
    if (res) {
      exForm = res.data
    } else {
      Taro.hideToast()
    }
    exForm.is_supplier = 1
    exForm.is_app = 1
    exForm.supplier_id = this.state.queryData['supplier_id']
    exForm.is_push = 'true'
    exForm.uuid=uuid
    const data = await http.postCar(ALIBABA_UPDATE_ALIBABAGOODS, exForm)
    if (data) {
      Taro.showToast({
        title: '操作成功',
        icon: 'none',
        duration: 2000
      })
      this.getList()
    } else {
      setTimeout(function(){
        Taro.showToast({
          title: data.message,
          icon: 'none',
          duration: 2000
        })
      }, 1000)
    }
  }

  onChange(e) {
    const {supplierList, queryData} = this.state
    this.page = 1
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    queryData['pageNumber'] = 1
    queryData['supplier_id'] = supplierList[supplierIndex].supplier_id
    this.setState({supplierIndex, supplierChecked})
    Taro.setStorageSync('mySupplierIndex', supplierIndex)
    this.getList()
  }
  // 上下架
  async shelf(action, uuid) {
    const params = {
      action: action,
      item_id: uuid,
      is_app: 1,
      is_supplier: 1
    }
    const res = await http.MPost( ALIBABA_SYNC_NOTICE_GOODS, params)
    if (res) {
      this.getList()
    }
  }

  handleClick(value) {
    this.setState({
      currentSearchIndex: value
    }, async () => {this.getList()})

  }

  render() {
    const {
      list,
      supplierList,
      supplierIndex,
      supplierChecked,
      queryData,
      searchList,
      currentSearchIndex,
      loadMoreStatus,
      failMessage
    } = this.state
    return (
      <View className='shopcar-root regional-category-shop aliGoodsList'>
        <GzhAuth />
        <View className='search-top'>
          <View className='header-top' style={`background-color: ${process.env.mainColor}`}>
            <View className='head-picker'>
              {!!supplierList && supplierList.length >= 1 &&
              <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
                <View className={supplierChecked ? 'picker' : 'picker off'}>
                  {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                  <Text>切换</Text>
                </View>
              </Picker>}
            </View>
            <View className='input-box'>
              <View className='input input-i-cla'>
                <Input placeholderClass='input_pla' placeholder='请输入商品名称/商品编码'
                  onInput={({detail: {value}}) => {
                         let {thirdStoreName} = this.state
                         thirdStoreName = value;
                         this.setState({thirdStoreName})
                       }}
                />
              </View>
              <View className='btn' onClick={this.searchConfirm.bind(this)}><AtIcon prefixClass='xxhz' value='sousuo2'
                size='18' color='#fff'
              /></View>
            </View>
          </View>
        </View>
        <AtTabs
          scroll
          className='search-tabs'
          current={currentSearchIndex}
          tabList={searchList}
          onClick={this.handleClick.bind(this)}
        >
        </AtTabs>
        <View className='product-list'>
          {
            list && list.length > 0 && list.map((item, index) =>
              <View className='product-list-item' key={index}>
                <View className='product-list-item-head'>
                  <View className='product-list-item-right'>{item.no}</View>
                  <View
                    className={`product-list-item-name ${item.status == '审核失败' ? 'red-font' : item.status == '审核成功' ? 'green-font' : item.status == '审核中' ? 'blue-font': item.status == '待提交' ? 'yellow-font' : ''}`}
                    style='-webkit-box-orient: vertical;'
                    onClick={this.showTips.bind(this, item.error_message, item.status)}
                  >{item.status}
                    {item.status == '审核失败' && <View className='product-list-item-name-tips'>
                      <View className='aticon'>
                        <AtIcon value='help'
                          customStyle='vertical-align:middle !important;font-weight: bold;'
                          size='15'
                          color='#ff0101'
                        /></View>
                    </View>}
                  </View>
                </View>
                <View className='line' />
                <View className='product-list-item-content'>
                  <View className='product-list-item-content-pic'>
                    <Image className='left-img' mode='aspectFill'
                      src={item.cover}
                    />
                  </View>
                  <View className='product-list-item-content-title'>
                    <View className='product-list-item-content-title-title'>{item.gname}</View>
                    <View className='product-list-item-content-title-num'>库存：{item.inventory}件</View>
                    <View className='product-list-item-content-title-price'>
                      <View className='product-list-item-content-title-price-original'>￥{item.original_price}</View>
                      <View className='product-list-item-content-title-price-price'>￥{item.price}</View>
                    </View>
                  </View>
                </View>
                <View className='product-list-item-btn'>
                  {item.online_status=='下架' && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => this.shelf('resume', item.item_id)}
                    >上架</AtButton>
                  </View>}
                  {item.online_status=='上架' && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => this.shelf('pause', item.item_id)}
                    >下架</AtButton>
                  </View>}
                  {item.showEdit && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => Taro.navigateTo({url: '/other/aliLocalLife/supplier/index?uuid=' + item.uuid + "&type=" + 0 + "&status=" + item.status + "&supplierId=" + queryData['supplier_id']})}
                    >编辑</AtButton>
                  </View>}
                  {item.showSee && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => Taro.navigateTo({url: '/other/aliLocalLife/supplier/index?uuid=' + item.uuid + "&type=" + 1 + "&sale_style=" + item.status + "&supplierId=" + queryData['supplier_id']})}
                    >查看</AtButton>
                  </View>}
                  {item.showDelete && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => this.deleteGoods(item.uuid)}
                    >删除</AtButton>
                  </View>}
                  {/*{item.showEditStock && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                              onClick={() => Taro.navigateTo({url: '/main/productForm/index?id=' + item.id + "&type=" + encodeURIComponent(item.tadpole_goods_type) + "&sale_style=" + item.sale_style})}
                    >库存修改</AtButton>
                  </View>}*/}
                  {item.showAliDelete && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() =>  this.deleteGoods(item.uuid, 'invalid')}
                    >阿里商品删除</AtButton>
                  </View>}
                  {item.showPush && <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                      onClick={() => this.examine(item.uuid)}
                    >提交审核</AtButton>
                  </View>}
                </View>
              </View>)
          }
          {(list && list.length == 0) && loadMoreStatus != 'loading' && <View className='product-list-null-product'>
            <Image src='https://resource.ivcheng.com/resources/images/shopnull.png' mode='widthFix' />
          </View>}
        </View>
        <View style='height: 65px;'></View>
        <View
          className={process.env.TARO_ENV === 'h5' ? "addInfo h5-small" : "addInfo"}
          style={`background-color: ${process.env.mainColor}`}
          onClick={
            () => Taro.navigateTo({url: '/other/aliLocalLife/supplier/index?supplierId='+ queryData['supplier_id']})
          }
        >创建商品</View>

        {failMessage.show && <View className='box-model'>
          <View className='box-show_code_bj'></View>
          <View className='box-show_code_content'>
            <View className='box-show_code_content-title'>详情</View>
            <View className='box-show_code_content-message'>{failMessage.message}</View>
            <View className='box-show_code_content-btn'>
              <View className='box-show_code_content-btn-btn'
                onClick={() => this.closeModel()}
              >
                关闭
              </View>
            </View>
          </View>
        </View>}

        <View style='height: 10px' />
      </View>
    )
  }
}

export default Index as ComponentClass
